﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Windows.Media.Animation;

namespace Game
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private const double BOARD_WIDTH = 50;
        private const double BOARD_HEIGHT = 10;

        private DispatcherTimer _timerUpdate;
        private DispatcherTimer _timerCreate;
        private double _y;

        private Random _random = new Random();

        public MainWindow()
        {
            InitializeComponent();

            Init();
        }

        private void Init()
        {
            _y = 0;

            InitTimerUpdate();
            InitTimerCreate();
        }

        private void InitTimerUpdate()
        {
            _timerUpdate = new DispatcherTimer();
            _timerUpdate.Tick += Timer_Tick;
            _timerUpdate.Interval = TimeSpan.FromMilliseconds(10);
            _timerUpdate.Start();
        }

        void Timer_Tick(object sender, EventArgs e)
        {
            _y = (_y + 6) % canvasStage.ActualHeight;
            Canvas.SetTop(board, _y);
        }

        private void InitTimerCreate()
        {
            _timerCreate = new DispatcherTimer();
            _timerCreate.Tick += TimerCreate_Tick;
            _timerCreate.Interval = TimeSpan.FromMilliseconds(300);
            _timerCreate.Start();
        }

        private void TimerCreate_Tick(object sender, EventArgs e)
        {
            Rectangle board = new Rectangle()
                {
                    Width = BOARD_WIDTH,
                    Height = BOARD_HEIGHT
                };
            double x = GetRandBoardPos();
            Canvas.SetLeft(board, x);

            canvasStage.Children.Add(board);

            Storyboard storyboard = new Storyboard();
            DoubleAnimation doubleAnimation = new DoubleAnimation(
                canvasStage.ActualHeight,
                -BOARD_HEIGHT,
                new Duration(TimeSpan.FromMilliseconds(500)));
            Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Top)"));
            storyboard.Children.Add(doubleAnimation);

            storyboard.Begin();
        }

        private double GetRandBoardPos()
        {
            return _random.NextDouble() * (canvasStage.ActualWidth - BOARD_WIDTH);
        }
    }
}
